#include <stdio.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <unistd.h>
#include <sys/sem.h>



union semnum
{
	int semval;
};

int seminit(int semid,int semnum,int val)
{
	union semnum semctrl;
	semctrl.semval=val;
	semctl(semid,semnum,SETVAL,semctrl);

	return 0;
}

int sem_p(int semid,int semnum)
{
	struct sembuf mysem;
	mysem.sem_num=semnum;
	mysem.sem_op=-1;
	mysem.sem_flg=0;

	semop(semid,&mysem,1);

	return 0;
}
int sem_v(int semid,int semnum)
{
	struct sembuf mysem;
	mysem.sem_num=semnum;
	mysem.sem_op=1;
	mysem.sem_flg=0;

	semop(semid,&mysem,1);

	return 0;
}


int main(int argc, const char *argv[])
{
	key_t key1=ftok("./1.txt",'c');
	key_t key2=ftok("./1.txt",'d');

	int shmgid=shmget(key1,4096,IPC_CREAT|0664);
	char *buf=shmat(shmgid,NULL,0);

	int semid=semget(key2,2,IPC_CREAT|0664);

	seminit(semid,0,1);
	seminit(semid,1,0);

	pid_t pid = fork();

	if(pid>0)
	{
		while(1)
		{
			sem_p(semid,0);
			scanf("%s",buf);
			sem_v(semid,1);
		}
	}
	else if(pid ==0)
	{
		while(1)
		{
			sem_p(semid,1);
			printf("buf : %s\n",buf);
			sem_v(semid,0);
		}
	}

	return 0;
}
